from mxit.binary import BinaryStream
from mxit.errors import *
from mxit.encryption import decrypt
from mxit import handles
import excepts
import binascii
import gtk
import datetime

"""
   This module can read MXM files.
"""


class mxmReader:

   type = 2;
   encrypted = False;
   messages = [];

   def __init__(self,data):
      # Do a check on the data
      if not data.startswith("MXM"):
         raise excepts.MalformedMXMData;
         return;

      self.stream = BinaryStream(None, data);
      type, = self.stream.read('I');
      if type == 0x4d584d01:
         # MXM V1
         self.type = 1;
      elif type in (0x4d584d02,0x4d584d04):
         # MXM V2
         self.type = 2;
         if type == 0x4d584d04:
            # Encyrpted MXM file
            self.encrypted = True;

   def decrypt(self,key):
      try:
         text = decrypt(entry.get_text(),self.stream.data);
         self.stream = BinaryStream(None,text);
         return True;
      except MxitException:
         return False;

   def parse(self):
      if self.type == 1:
         self.parseVOne();
      elif self.type == 2:
         self.parseVTwo();
      
      return self.messages;

   def parseVOne(self):
      nmsgs, = self.stream.read('I');
      for i in range(0,nmsgs):
         ts,fa,ta,body = self.stream.read('QSSS');
         
         # Message
         bud = handles.Buddy('',fa,'');
         timestamp = datetime.datetime.fromtimestamp(ts);
         mesg = handles.Message(bud,body,timestamp,[]);
         self.messages.append(mesg);

   def parseVTwo(self):
      four,nmsgs = self.stream.read('II');
      
      for i in range(0,nmsgs):
         ln,ts,fa,ta,body,r = self.stream.read('IQSSSI');

         # Decode the flags
         flags = [];
         for flag in handles.MessageFlags.lookup:
            value = int(handles.MessageFlags.lookup[flag].id);
            bit = r ^ value;
            if bit < r:
               flags.append(handles.MessageFlags.byid(value));
               r = bit;

         # Message
         bud = handles.Buddy('',fa,'');
         timestamp = datetime.datetime.fromtimestamp(ts);
         mesg = handles.Message(bud,body,timestamp,flags);
         self.messages.append(mesg);
